<template>
    <div class="shopping">
        <van-nav-bar title="购物车" right-text="删除" @click-right="delGoods(state.dish_dish_ids)" />
        <div class="cart">
            <h3>火锅烧烤</h3>
            <van-checkbox-group v-model="state.checked" @change="change3()">
                <van-checkbox :name="item.dish_id" label-disabled v-for="item in state.orderList" @change="change()">
                    <div class="header">
                        <van-image :src="item.image" />
                        <div class="detail">
                            <span class="title">{{ item.name }}</span>
                            <div class="price">
                                <span>￥<span class="rmb">{{ item.price }}</span></span>
                                <van-field name="stepper">
                                    <template #input>
                                        <van-stepper @minus="() => { }" @change="change(item.id, item.number, item.dish_id)"
                                            v-model="item.number" theme="round" button-size="28" min="0" />
                                    </template>
                                </van-field>
                            </div>
                        </div>
                    </div>
                </van-checkbox>
            </van-checkbox-group>
        </div>
        <div class="divider">
            <van-divider
                :style="{ color: 'black', borderColor: 'rgb(200, 200, 200)', padding: '0 16px' }">热卖商品</van-divider>
        </div>
        <div class="hot-selling">
            <GoodsList :goodsList="state.goodsList" @child-click="zCf" />
        </div>
        <van-submit-bar button-color="#00a73c" :price="state.total_price * 100" button-text="结算" @submit="updateshop()">
            <van-checkbox v-model="state.checked2" @click="selectAll()">全选</van-checkbox>
        </van-submit-bar>
        <van-back-top style="background-color: #5ac6f5;" bottom="3rem" right="1.3rem" />
        <TabBar :cart_badge="cartCount" />
    </div>
</template>
<script setup>
import GoodsList from '../components/GoodsList.vue'
import TabBar from '../components/Tabbar.vue'
import axios from '../utils/axios.js'
import { showConfirmDialog } from 'vant';
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { onMounted, computed, reactive } from 'vue'
const router = useRouter()
const store = useStore()
const zCf = () => {
    getCart()
}

const state = reactive({
    // 菜品列表
    goodsList: [],
    // 购物车列表
    orderList: [],
    // 选中订单id集合
    dish_ids: [],
    // 总价格
    total_price: 0,
    // 被选中商品的下标集合
    checked: [],
    checked2: false,
})
// 获取购物车数据
const getCart = () => {
    axios.get('/inquire_shop').then((res) => {
        state.orderList = res.data
        change2()
        console.log(state.orderList);
        console.log(state.checked);
        // 借助vuex中的actions方法，更新当前加购商品总数
        store.dispatch('fetchCartCount')
    })
}
// 当前加购商品总数
const cartCount = computed(() => store.state.cartCount)
// 查询购物车订单
onMounted(() => {
    // 热卖商品数据
    axios.get('/inquire').then((res) => {
        state.goodsList = res.data
    })
    // 购物车数据
    getCart()
    allUnselected()
})

// 计算总价
const totalPrice = () => {
    state.total_price = 0
    state.checked.forEach((item1) => {
        state.orderList.forEach((item2) => {
            if (item1 === item2.dish_id) {
                state.total_price += item2.price * item2.number;
            }
        })
    })
}

// 选中全部
const selectAll = () => {
    console.log(state.checked2);
    if (state.checked2) {
        state.orderList.forEach((item) => {
            if (!state.checked.includes(item.dish_id)) {
                state.checked.push(item.dish_id)
            }
        })
        totalPrice()
    }
    else {
        state.checked = []
    }

}

// 修改商品选中状态时触发方法
const change3 = () => {
    console.log(state.orderList);
    console.log(state.checked);
    totalPrice()
    if (state.orderList.length === 0) {
        state.checked2 = false
    }
    else if (state.checked.length < state.orderList.length) {
        console.log(2);
        state.checked2 = false
    }
    else if (state.checked.length === state.orderList.length) {
        console.log(1);
        state.checked2 = true
    }
}

// 当选中状态的商品被删除时触发该方法更新state.checked
const change2 = () => {
    let arr = state.orderList.map(item => (item.dish_id))
    // console.log(arr);
    if (arr.length === 0) {
        state.checked = []
    }
    else {
        state.checked.forEach((item, index) => {
            if (!arr.includes(item)) {
                state.checked.splice(index, 1)
            }
        })
        if (arr.length === state.checked.length && state.checked2 === false) {
            state.checked2 = true
        }
        else if (state.checked2 && state.checked.length < arr.length) {
            state.checked2 = false
        }
        // else if (!state.checked2 && state.checked.length < arr.length) {
        //     state.checked2 = false
        // }
    }
}

// 或添加和减少菜品数量时触发方法
const change = (id, num, dish_id) => {
    console.log(state.checked);
    totalPrice()
    if (num === 0) {
        subdel(id, dish_id)
    }
    else {
        axios.post('/update_shop_add', { id: id, number: num }).then((res) => {
            getCart()
        })
    }
}

// 购物车中商品数量减少为0时触发的删除事件，出现弹出框挽留用户
const subdel = (id, dish_id) => {
    showConfirmDialog({
        title: '提示',
        message:
            '确定要将该商品从购物车中删除吗',
    }).then(() => {
        // 点击确认时
        axios.post('/delete_shop', { ids: dish_id }).then((res) => {
            // console.log(res);
            getCart()
        })
    }).catch(() => {
        // 点击取消时
        axios.post('/update_shop_add', { id: id, number: 1 }).then((res) => {
            getCart()
        })
    });
}

// 删除购物车中选中的商品
const delGoods = () => {
    console.log();
    axios.get('/inquire_shop').then((res) => {
        if (res.data.length !== 0) {
            if (state.checked.length > 0) {
                showConfirmDialog({
                    title: '提示',
                    message:
                        '确定要将该商品从购物车中删除吗',
                }).then(() => {
                    // 点击确认时
                    axios.post('/delete_shop', { ids: state.checked }).then((res) => {
                        state.total_price = 0
                        state.checked = []
                        getCart()
                    })
                }).catch(() => {
                    // 点击取消时
                });
            }
        }
    })
}

// 点击结算时更新选中状态，跳转至订单页
const updateshop = () => {
    const ids = state.checked; // 获取选中的ID值
    if (ids.length > 0) {
        axios.post('/inquire_shop_selected', { ids: ids }).then((res) => {
            console.log(res.code);
            if (res.code === 200) {
                router.push('/order')
            }
        })
    }
}

// 进入购物车页时更新全部商品为未选中状态
const allUnselected = () => {
    axios.post('/inquire_shop_unselected').then((res) => {
        // console.log(res.code);
    })
}

</script>
<style scoped>
.shopping {
    width: 100%;
    background-color: rgb(247, 247, 247);
}

.van-nav-bar {
    background-color: rgb(247, 247, 247);
}

.cart-li {
    display: flex;
}

.cart {
    max-width: 430px;
}

.cart>h3 {
    height: 1rem;
    line-height: 1rem;
    font-size: 18px;
    font-family: '宋体';
    padding-left: 0.3rem;
    font-weight: bold;
}

.cart .van-checkbox {
    width: 90%;
    background-color: #fff;
    margin: 0 auto;
    border-radius: 10px;
    padding: 0.24rem;
    margin-bottom: 0.2rem;
}

.van-checkbox__label {
    width: 100%;
}

.cart .header {
    padding: 0.1rem 0.3rem;
    display: flex;
}

.cart .header .detail {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding-left: 0.2rem;
    width: 100%;
}

.cart .header .detail span {
    font-size: 16px;
}

.cart .header .detail .price {
    color: rgb(220, 64, 64);
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
}

.cart .header .detail .price span {
    line-height: 36px;
}

.cart .header .detail .price .rmb {
    font-size: 24px;
}

.hot-selling {
    padding-bottom: 100px;
}


</style>

<style>
/* 步进器按钮颜色覆盖 */
:root {
    --van-stepper-button-round-theme-color: #00a73c;
}

.van-dialog {
    width: 90%;
    text-align: center;
    background-color: rgb(28, 28, 30);
    color: #fff;
    border-radius: 10px;
    transition: none;
}

.van-dialog__header {
    font-size: 22px;
    padding: 10px 0;
}

.van-dialog__message--has-title {
    font-size: 16px;
    padding: 1rem 0;
    color: gray;
}

.van-dialog__footer {
    display: flex;
}

.van-dialog__confirm,
.van-dialog__cancel {
    background-color: rgb(28, 28, 30);
    color: #fff;
    border: none;

}

.van-dialog__confirm,
.van-dialog__cancel:active {
    background-color: rgb(28, 28, 30, .5);
}

.van-dialog__confirm,
.van-dialog__cancel:focus {
    background-color: rgb(28, 28, 30, .5);
}
</style>